import { createNotify, createTable } from "./createElements.js";

let sortFlag = 1;

const submitData = async (event) => {
  event.preventDefault();
  const form = event.target;
  const data = {
    breed: form.breed.value,
    imageurl: form.imageurl.value,
    age: form.age.value,
  };

  const responce = await fetch("/add_cat", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });

  form.reset();
  if (responce.ok) {
    createNotify();
    const data = await getAllCats();
    if (createTable(data)) addEvent(data);
  }
};

const deleteById = (event) => {
  event.preventDefault();
  const button = event.target;
  const data = {
    id: +button.name,
  };

  fetch("/delete_cat", {
    method: "DELETE",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  }).finally(async () => {
    const data = await getAllCats();
    if (createTable(data)) addEvent(data);
  });
};

const getAllCats = async () => {
  const response = await fetch("/get_cats");
  return response.ok ? await response.json() : {};
};

const getSortCats = async (event) => {
  event.preventDefault();
  const form = event.target;
  const data = {
    breed: form.breed.value,
    age: form.age.value,
    size: form.size.value,
  };
  const responce = await fetch(
    `/sort_cats?breed=${data.breed}&age=${data.age}&size=${data.size}`,
    {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    }
  );
  if (responce.ok) {
    const data = await responce.json();
    if (createTable(data)) addEvent(data);
  }
};

const getSortByAge = async () => {
  const responce = await fetch(`/sort_age?sort=${sortFlag}`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
  });
  if (responce.ok) {
    const data = await responce.json();
    if (createTable(data)) addEvent(data);
  }
};

const addEvent = (data) => {
  data.forEach((e, index) =>
    document
      .getElementById(`delete_data_${index}`)
      .addEventListener("click", deleteById)
  );
  document.getElementById("sort_age").addEventListener("click", () => {
    sortFlag = sortFlag === 0 ? 1 : 0;
    getSortByAge();
  });
};

document.getElementById("submit_cat").addEventListener("submit", submitData);
document.getElementById("sort_cats").addEventListener("submit", getSortCats);
